<?php

/**
 * 商品分类
 */

namespace app\admin\service;

use function think\db\findOrEmpty;
use think\Service;
use app\admin\model\ProductCategory as CategoryModel;
use app\admin\model\Images;

class Category extends BaseService
{

    /**
     * 获取分类列表
     * @param $param
     * @param $page
     * @param $limit
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList($param = [], $page = 1, $limit = 10)
    {
        $where = [['is_del','=',0]];
        $arrData = ['code' => 0, 'message' => 'success'];
        if ($param['name']) {
            $where[] = ['name', 'like', '%' . $param['name'] . '%'];
        }

        $oCategoryModel = CategoryModel::where($where);
        $total = $oCategoryModel->count();
        $result = $oCategoryModel->with(['get_creator_name', 'get_update_name'])->page($page, $limit)->order('id', 'desc')->select()->toArray();
        $result = CategoryModel::addParentName($result);
        $arrData['data'] = ['list' => $result, 'total' => $total];
        return $arrData;
    }

    /**
     * 删除单条或多条分类数据
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete($param)
    {
        // 将逗号分隔的ID转为数组
        $rawIds = explode(',', $param['ids']);
        $rawIds = array_map('intval', $rawIds);

        // 查询存在子分类的父级ID
        $parentWithChildIds = CategoryModel::whereIn('parent_id', $rawIds)
            ->where('is_del', 0)
            ->column('parent_id');
        $uniqueIds = array_unique($parentWithChildIds);
        // 过滤掉有子类的父级ID
        $safeDeleteIds = array_diff($rawIds, $uniqueIds);

        // 无有效ID可删除的情况处理
        if (empty($safeDeleteIds)) {
            return [
                'code' => 1,
                'message' => "存在子分类，禁止删除"
            ];
        }

        // 执行批量删除（网页[2]的IN语句优化）
        $result = CategoryModel::whereIn('id', $safeDeleteIds)
            ->where('is_del', 0)
            ->update(['is_del' => time()]);

        if ($result) {
            $this->clearCTerminalCache(4); // 清除C端产品缓存
            $this->logger->logOperation(
                $safeDeleteIds,
                'category',
                '删除',
                '安全删除分类'
            );
            return ['code' => 0, 'message' => '成功删除'.count($safeDeleteIds).'个分类'];
        }

        return ['code' => 1, 'message' => '删除失败'];
    }

    /**
     * 添加修改分类
     * @param $param
     * @return array|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save($param)
    {
        $checkCategoryModel = CategoryModel::where([['name','=', $param['name']], ['is_del', '=', 0]]);
        if ($param['id']) {
            $checkCategoryModel->where('id', '<>', $param['id']);
        }
        if ($checkCategoryModel->find()) {
            return ['code' => 1, 'message' => '分类名称重复！'];
        }

        if ($param['id']) {
            $oCategoryModel = CategoryModel::find($param['id']);
            $oCategoryModel->updater = $param['operator_id'];
            $oCategoryModel->update_time = date('Y-m-d H:i:s', time());
        } else {
            $oCategoryModel = new CategoryModel();
            $oCategoryModel->creator = $param['operator_id'];
            $oCategoryModel->create_time = date('Y-m-d H:i:s', time());
            $oCategoryModel->is_del = 0;
        }

        $oCategoryModel->name = $param['name'];
        $oCategoryModel->image = $param['image'];
        $oCategoryModel->sort_order = $param['sort_order'];
        $oCategoryModel->description = $param['description'];
        $oCategoryModel->parent_id = $param['parent_id'];
        $oCategoryModel->solution_type = $param['solution_type'];

        if ($oCategoryModel->save()) {
            $this->clearCTerminalCache(4); // 清除C端产品缓存
            $this->logger->logOperation($oCategoryModel->id,'category','添加/保存','添加/保存分类');
            return ['code' => 0, 'message' => '保存分类成功！'];
        }
    }

    /**
     * 获取单个分类信息
     * @param int $id 分类ID
     * @return array
     */
    public function getInfo($param)
    {
        $where = [['is_del', '=', '0'], ['id', '=', $param['id']]];
        $oCategoryModel = CategoryModel::where($where)->with(['get_creator_name', 'get_update_name'])->find();

        if (!$oCategoryModel) {
            return ['code' => 1, 'message' => '获取分类信息失败！'];
        }
        #先取图片数据
        $oCategoryModel['imageInfo'] = [];
        if($oCategoryModel['image']){
            $oImages = new Images();
            $imageUrl = $oImages->getImagesByIds($oCategoryModel['image']);
            $oCategoryModel['imageInfo'] = $imageUrl;
        }
        #取父级分类名称
        $oCategoryModel = CategoryModel::addParentName([$oCategoryModel]);
        return ['code' => 0, 'message' => 'success', 'data' => $oCategoryModel[0]];
    }

    /**
     * 下拉框选择接口
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getSelect()
    {
        $where = [['is_del','=',0]];
        $arrData = ['code' => 0, 'message' => 'success'];

        $field = ['id', 'name'];
        $oCategoryModel = CategoryModel::where($where)->whereNull('parent_id');
        $total = $oCategoryModel->count();
        $result = $oCategoryModel->field('id AS value,name as label')->select();
        $result = $result->toArray();
        #value 强制转换int   todo可以写一个公共方法 支持多维数组 多字段转换类型
        array_walk($result, function(&$item) {
            $item['value'] = (int)$item['value'];
        });
//        array_unshift($result, ['value'=>0,'label'=>'顶级分类']);
        $arrData['data'] = ['list' => $result, 'total' => $total];
        return $arrData;
    }
    /**
     * 下拉框选择接口
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getSelectTree()
    {
        $where = [['is_del','=',0]];
        $arrData = ['code' => 0, 'message' => 'success'];

        $oCategoryModel = CategoryModel::where($where);
        $total = $oCategoryModel->count();
        $result = $oCategoryModel->field('id AS value,name as label,parent_id')->select();
        $result = $result->toArray();
//        array_unshift($result, ['value'=>0,'label'=>'顶级分类']);
        $categoryTree = generateTree($result);
        $arrData['data'] = ['list' => $categoryTree, 'total' => $total];
        return $arrData;
    }
}
